﻿/*  
    Copyright (C) <2007-2013>  <Kay Diefenthal>

    ArgusTv.UI.MediaCenter is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    ArgusTv.UI.MediaCenter is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with ArgusTv.UI.MediaCenter.  If not, see <http://www.gnu.org/licenses/>.
*/

using System;
using System.Collections.Generic;
using ArgusTV.DataContracts;
using ArgusTV.ServiceAgents;
using ArgusTV.UI.MediaCenter.Logging;
using ArgusTV.UI.MediaCenter.Models;
using ArgusTV.UI.MediaCenter.Views;
using Microsoft.MediaCenter;
using Microsoft.MediaCenter.Hosting;
using Microsoft.MediaCenter.UI;

namespace ArgusTV.UI.MediaCenter.ViewModels
{
    public class EpgModel : ModelItem
    {
        #region Private Fields

        private readonly HistoryOrientedPageSession _session;
        private readonly AddInHost _host;
        private readonly ChannelType _channelType;

        #endregion

        #region Constructors

        /// <summary>
        /// EpgModel
        /// </summary>
        public EpgModel() : this(null, null, 0)
        {
        }

        /// <summary>
        /// EpgModel
        /// </summary>
        /// <param name="session"></param>
        /// <param name="host"></param>
        /// <param name="type"></param>
        public EpgModel(HistoryOrientedPageSession session, AddInHost host, Int32 type)
        {
            _session = session;
            _host = host;
            _channelType = (ChannelType) type;
        }

        #endregion

        #region Properties

        /// <summary>
        /// 
        /// </summary>
        public MediaCenterEnvironment MediaCenterEnvironment
        {
            get
            {
                if (_host == null) return null;
                return _host.MediaCenterEnvironment;
            }
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// MultiChannelEpgView
        /// </summary>
        /// <returns></returns>
        private MultiChannelEpgView CreateMultiChannelEpgView()
        {
            var view = new MultiChannelEpgView
                {
                    ListingItemOffer = new ListingItemOffer(),
                    CurrentFilterCommand = new FilterCommand()
                };

            CreateFilterCommands(view);

           
            
            
            return view;
        }

        /// <summary>
        /// CreateFilterCommands
        /// </summary>
        /// <param name="view"></param>
        private void CreateFilterCommands(MultiChannelEpgView view)
        {
            var list= new ArrayListDataSet();
            using (var schedulerServiceAgent = new SchedulerServiceAgent())
            {
                var channelGroups = schedulerServiceAgent.GetAllChannelGroups(_channelType, true);
                foreach (var channelGroup in channelGroups)
                {
                    list.Add(CreateFilterCommand(channelGroup.ChannelGroupId, channelGroup.GroupName));
                }
            }
            view.FilterCommandChanged += delegate(object sender, EventArgs args)
                {
                    var command = (FilterCommand)sender;
                    CreateFilteredContent(view, command.UniqueId);
                };
            view.CurrentFilterCommand = (FilterCommand)list[0];
            CreateFilteredContent(view, view.CurrentFilterCommand.UniqueId);
            view.FilterCommands = list;
        }

        /// <summary>
        /// CreateFilteredContent
        /// </summary>
        /// <param name="view"></param>
        /// <param name="uniqueId"></param>
        private void CreateFilteredContent(MultiChannelEpgView view, Guid uniqueId)
        {
            var list=new ArrayListDataSet();
            using (var schedulerServiceAgent = new SchedulerServiceAgent())
            {
                var channels = schedulerServiceAgent.GetChannelsInGroup(uniqueId, true);
                {
                    foreach (var channel in channels)
                    {
                        list.Add(CreateRowHeader(channel.ChannelId, channel.DisplayName));
                    }
                }
            }
            view.FilteredContent = list;

        }

        /// <summary>
        /// CreateFilterCommand
        /// </summary>
        /// <param name="uniqueId"></param>
        /// <param name="description"></param>
        /// <returns></returns>
        private FilterCommand CreateFilterCommand(Guid uniqueId, String description)
        {
            var command = new FilterCommand
                {
                    UniqueId = uniqueId,
                    Description = description
                };
            return command;
        }

        /// <summary>
        /// CreateRowHeader
        /// </summary>
        /// <param name="uniqueId"></param>
        /// <param name="description"></param>
        /// <returns></returns>
        private RowHeader CreateRowHeader(Guid uniqueId, String description)
        {
            var command = new RowHeader
                {
                    UniqueId = uniqueId,
                    Description = description
                };

            command.Invoked += delegate(object sender, EventArgs args)
                {
                    var item = (RowHeader) sender;
                    GoToSingelChannelEpgView(CreateSingelChannelEpgView(item.UniqueId));
                };
            return command;
        }

        /// <summary>
        /// CreateSingelChannelEpgView
        /// </summary>
        /// <param name="uniqueId"></param>
        /// <returns></returns>
        private SingelChannelEpgView CreateSingelChannelEpgView(Guid uniqueId)
        {
            using (var schedulerServiceAgent = new SchedulerServiceAgent())
            {
                var channel = schedulerServiceAgent.GetChannelById(uniqueId);
                var singelChannelEpgView = new SingelChannelEpgView();
                var start = DateTime.Now;
                var stop = start.AddDays(7.0);
                var contentlist = new VirtualList
                    {
                        EnableSlowDataRequests = true
                    };
                singelChannelEpgView.ChannelName = channel.DisplayName;
                singelChannelEpgView.ChannelListings = contentlist;
                singelChannelEpgView.ListingItemOffer = new ListingItemOffer();
                if (channel.GuideChannelId.HasValue)
                {
                    using (var guideServiceAgent = new GuideServiceAgent())
                    {
                        var summaryarray = guideServiceAgent.GetChannelProgramsBetween(channel.GuideChannelId.Value,start, stop);
                        //for (int i = 0; i < summaryarray.Length; i++)
                        //{
                        //    //contentlist.Add(CreateColumnForGuideProgram(guideServiceAgent.GetProgramById(summaryarray[i].GuideProgramId), 450, i));
                        //}
                    }
                }
                //else
                //{
                //    //contentlist.Add(CreateColumn("", 400));
                //}
                return singelChannelEpgView;
            }
        }

        /// <summary>
        /// Creates a DetailsView User Interface for GuideProgram
        /// </summary>
        /// <returns></returns>
        private DetailsView CreateDetailsView(GuideProgram program)
        {
            var detailsView = new DetailsView
                {
                    Title = string.Format("{0}{1}", program.Title + " - ", program.SubTitle),
                    Metadata = string.Format("{0}{1}{2}", program.StartTime.ToShortDateString() + ", ",
                                             program.StartTime.ToShortTimeString() + " - ",
                                             program.StopTime.ToShortTimeString()),
                    Summary = program.Description
                };
            var commands = new ArrayListDataSet();
            detailsView.Commands = commands;
            return detailsView;
        }

        /// <summary>
        /// GoTo SingelChannelEpgView
        /// </summary>
        /// <param name="singelChannelEpgView"></param>
        private void GoToSingelChannelEpgView(SingelChannelEpgView singelChannelEpgView)
        {
            try
            {
                var uiProperties = new Dictionary<string, object>();
                uiProperties["SingelChannelEpgView"] = singelChannelEpgView;
                _session.GoToPage("resx://ArgusTV.UI.MediaCenter/ArgusTV.UI.MediaCenter.Resources/SingelChannelEpgView", uiProperties);
            }
            catch (Exception exception)
            {
                Logger.Error(string.Format("{0}{1}:{2}", "EpgModel", "GoToSingelChannelEpgView", exception));
            }
            
        }
        
        /// <summary>
        /// GoTo DetailsView
        /// </summary>
        /// <param name="detailsView"></param>
        private void GoToDetailsView(DetailsView detailsView)
        {
            try
            {
                var uiProperties = new Dictionary<string, object>();
                uiProperties["DetailsView"] = detailsView;
                _session.GoToPage("resx://ArgusTV.UI.MediaCenter/ArgusTV.UI.MediaCenter.Resources/DetailsView", uiProperties);
            }
            catch (Exception exception)
            {
                Logger.Error(string.Format("{0}{1}:{2}", "EpgModel", "GoToDetailsView", exception));
            }
            
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// GoToMultiChannelEpgView
        /// </summary>
        public void GoToMultiChannelEpgView()
        {
            try
            {
                var uiProperties = new Dictionary<string, object>();
                uiProperties["ViewModel"] = CreateMultiChannelEpgView();
                _session.GoToPage("resx://ArgusTV.UI.MediaCenter/ArgusTV.UI.MediaCenter.Resources/MultiChannelEpgView",uiProperties);
            }
            catch (Exception exception)
            {
                Logger.Error(string.Format("{0}{1}:{2}", "EpgModel", "GoToMultiChannelEpgView", exception));
            }
        }

        #endregion
    }
}
